package com.luguangtao.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luguangtao.entity.Goods;
import com.luguangtao.entity.GoodsExample;
import com.luguangtao.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class GoodsController1 {
    @Autowired
    GoodsMapper goodsMapper;

    //列表
    @RequestMapping("lists1")
    public PageInfo<Goods> lists1(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam String gsname,@RequestParam String ss){
        PageHelper.startPage(pageNum,3);
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        if(!StringUtils.isEmpty(gsname)){
            criteria.andGoodsnameLike('%'+gsname+'%');
        }
        if (!StringUtils.isEmpty(ss)){
            criteria.andStatusEqualTo(ss);
        }
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);
        return goodsPageInfo;
    }

    //添加
    @RequestMapping("addGoods1")
    public String addGoods1(@RequestBody Goods goods){
        goods.setDatea(goods.getDatea().substring(0,10));

        //获取价格   使价格有两位小数
        Double price = goods.getPrice();
        //正则验证
        String regEx = "^\\d+(\\.\\d{2})?$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(price.toString());
        boolean matches = matcher.matches();
        if (matches==false){
            return "error";
        }

        goodsMapper.insert(goods);
        return "success";
    }

    //删除
    @RequestMapping("del1")
    public String del1(@RequestParam String goodsid){
        goodsMapper.deleteByPrimaryKey(Integer.parseInt(goodsid));
        return "success";
    }

    //回显
    @RequestMapping("getGoods1")
    public Goods getGoods(@RequestParam String goodsid){
        Goods goods = goodsMapper.selectByPrimaryKey(Integer.parseInt(goodsid));
        return goods;
    }

    //修改
    @RequestMapping("updateGoods1")
    public String updateGoods1(@RequestBody Goods goods){
        goods.setDatea(goods.getDatea().substring(0,10));
        goodsMapper.updateByPrimaryKey(goods);
        return "success";
    }
}
